#! /usr/bin/env node
interface Meta {
    name: string
    description: string
    author: string
}
import program from 'commander'
import inquirer from 'inquirer';
import colors from 'colors'
// import download from 'download-git-repo';
import handlebars from 'handlebars';
import chalk from 'chalk';
import ora from 'ora';
// import shell from 'shelljs';
import child_process from 'child_process';
import fs from 'fs';
// import path from 'path';
class Template{
    static init(){
        program.version('0.0.5', '-v, --version')
        .command('init <name>')
        .action(name => {
            name = name ? name : 'ds-vue-template'
            const spinner = ora();
            spinner.color = 'green'
            spinner.text = '正在下载模板...\n'
            spinner.start()
            this.downloadGit(spinner,name)
        });
        program.parse(process.argv);
        
    }
    
    static editPackage(filename: string,meta: Meta){
        if (fs.existsSync(filename)) {
            const content = fs.readFileSync(filename).toString();
            let dt = JSON.parse(content);
            dt.name = '{{name}}';
            dt.description = '{{description}}'
            const result = handlebars.compile(JSON.stringify(dt, null, 2))(meta);
            fs.writeFileSync(filename, result);
            logger.success(chalk.green('项目初始化完成'));
            
            
          } else {
            logger.error(chalk.red('package不存在'))
          }
    }
    
    static downloadGit(spinner: ora.Ora,name: string){
        new Promise((resolve,reject)=>{
            child_process.exec(`git clone https://gitee.com/fhtwl/ds-vue-client.git ${name}`, (err)=>{
                spinner.text = '下载结束';
                if (err) {
                    spinner.fail('下载失败');
                    spinner.stop()
                    reject(err)
                } else {
                    spinner.succeed('下载成功');
                    spinner.stop()
                    inquirer.prompt([
                        {
                            name: 'description',
                            message: '请输入项目描述'
                        },
                        {
                            name: 'author',
                            message: '请输入作者名称'
                        }
                    ])
                    .then(info => {
                        const meta = {
                            name,
                            description: info.description,
                            author: info.author
                        }
                        const filename = `${name}/package.json`;
                        this.editPackage(filename,meta)
                        console.log(`下一步可执行 \n    $ cd ${name} \n    $ npm install \n    $ npm run serve`)
                        resolve(undefined)
                        
                        
                        
                    })
                    .catch(err=> {
                        logger.error(err)
                    })
                    
                }
                
            })
        
            
        }).catch(err=>{
            logger.error(err)
            logger.error(chalk.red('模板下载失败'))
        })
    }
    
    static async setProjectInfo(){
        return inquirer.prompt([
            {
                name: 'description',
                message: '请输入项目描述'
            },
            {
                name: 'author',
                message: '请输入作者名称'
            }
        ])
        // return prompt
    }
}
const logger = {
    success(msg: string){
        console.log(`[Success] ${colors.green(msg)}`);
    },
    info(msg: string){
      console.log(`[Info] ${colors.blue(msg)}`);
    },
    warn(msg: string){
      console.log(`[Warn] ${colors.yellow(msg)}`);
    },
    error(msg: string){
      console.log(`[Error] ${colors.red(msg)}`);
    }
};
Template.init()

